package com.apes.fn.scm.retailOrder.service.retailProcess.process;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.retailOrder.model.RetailOrder;
import com.apes.fn.scm.retailOrder.model.RetailOrderItem;
import com.apes.fn.scm.retailOrder.repository.RetailOrderItemRepository;
import com.apes.fn.scm.retailOrder.service.RetailInsuranceDiscountsService;
import com.apes.fn.scm.retailOrder.service.retailProcess.CommonRetailDataProcess;
import com.apes.fn.scm.retailReturn.RetailReturn;
import com.apes.fn.scm.retailReturn.RetailReturnItem;
import com.apes.fn.scm.retailReturn.RetailReturnRepository;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.soe.metadata.BusinessAttributeValue;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.frame.model.Store;
import com.apes.scm.masterdata.frame.repository.StoreRepository;
import com.apes.scm.masterdata.product.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import static java.util.stream.Collectors.toMap;

/**
 * 零售退回
 *
 * @author wuq
 * @create 2021-05-21 18:01
 */
@Service
public class RetailReturnProcess extends CommonRetailDataProcess {

    @Autowired
    private RetailOrderItemRepository orderItemRepository;
    @Autowired
    private RetailInsuranceDiscountsService retailInsuranceDiscountsService;

    @Override
    public void beforeSave(RetailOrder retailOrder) {
        beforeProcess(retailOrder, this::addRetailReturnInfo);
    }

    private void addRetailReturnInfo(RetailOrder saleOrder) {
        saleOrder.setSourceBusinessType("RetailReturn");
        saleOrder.setDateDone(new Date());
        saleOrder.setPostDate(new Date());

        String retailReturnId = saleOrder.getSource();
        saleOrder.setId(retailReturnId);     // 将零售退货单的单号，作为负零售单号
        RetailReturn retailReturn = SpringManager.getBean(RetailReturnRepository.class).findOne(retailReturnId);

        // 增加定损类型、案件类型
        if (retailReturn.getSaleOrder() != null) {
            saleOrder.setCaseType(retailReturn.getSaleOrder().getCaseType());
            saleOrder.setClaimType(retailReturn.getSaleOrder().getClaimType());
            saleOrder.setServiceDept(retailReturn.getSaleOrder().getServiceDept());
            saleOrder.setInsuranceCompany(retailReturn.getSaleOrder().getInsuranceCompany());
            saleOrder.setInsuranceReportNumber(retailReturn.getSaleOrder().getInsuranceReportNumber());
            saleOrder.setSource(retailReturn.getSaleOrder().getId());   // 修改 source 字段为零售单号
        }

        // 中石化门店退，将备注中的中石化单号放到指定的字段中
        Store store = SpringManager.getBean(StoreRepository.class).findByDept(saleOrder.getDept());
        if (store.isSinopec()) {
            saleOrder.setSinopecNumber(saleOrder.getRemark());
        }

        Map<String, RetailReturnItem> itemMap = retailReturn.getSaleItems().stream().collect(toMap(RetailReturnItem::getId, item -> item, (k1, k2) -> k1));
        saleOrder.getSaleItems().forEach(
                item -> {

                    // 退货订单原销售人员
                    RetailOrderItem itemOld = orderItemRepository.findByOriginAndOrdernumber(retailReturnId, item.getOriginnumber());
                    if (itemOld != null) {
                        item.setMainSalesman(itemOld.getMainSalesman());
                        item.setSubSalesman(itemOld.getSubSalesman());
                    }

                    if (itemMap.containsKey(item.getOriginnumber())) {
                        if (Objects.equals("SR003", retailReturn.getScene().getId())) {
                            // 零售有单退货
                            RetailReturnItem returnItem = itemMap.get(item.getOriginnumber());
                            item.setOriginalSalesUnitPrice(returnItem.getRetailOrderItem().getOriginalSalesUnitPrice());
                            item.setPriceOutUnitInTax(returnItem.getRetailOrderItem().getPriceOutUnitInTax());
                            item.setReferTax(returnItem.getRetailOrderItem().getReferTax());
                            item.setTax(returnItem.getRetailOrderItem().getTax());
                        } else {
                            // 零售无原单退货
                            RetailReturnItem returnItem = itemMap.get(item.getOriginnumber());
                            JSONObject price = getPrice(returnItem.getProduct(), retailReturn.getDept().getId());    // 获取定价过程
                            item.setOriginalSalesUnitPrice(price.getDoubleValue("Z002"));
                            item.setPriceOutUnitInTax(price.getDoubleValue("Z002"));
                            item.setReferTax(price.getDoubleValue("P008"));
                        }
                    }
                });

        BusinessAttributeValue businessAttributeValue = new BusinessAttributeValue();
        if ("A".equals(retailReturn.getOrderType().getCode())) {
            if (saleOrder.getSaleItems().stream().filter(retailOrderItem -> Objects.isNull(retailOrderItem.getOriginnumber()) || "".equals(retailOrderItem.getOriginnumber())).count() != 0) {
                throw new RuntimeException(String.format("零售退货(有原单) 不允许originnumber(来源明细)为空且必须为退单明细行号，请检查传参！APP订单号%s 零售退货单号%s", saleOrder.getOrigin(), retailReturnId));
            }
            businessAttributeValue.setId("RetailReturn.orderType.A");
            saleOrder.setReturnType(businessAttributeValue);
        } else {
            businessAttributeValue.setId("RetailReturn.orderType.B");
            saleOrder.setReturnType(businessAttributeValue);
        }
        invoke("fn.retail.return.retailDone", MapUtil.mapper("id", retailReturnId));


        // e 保养冲红单独处理
        if (!Objects.isNull(retailReturn.getSaleOrder()) && !Objects.isNull(retailReturn.getSaleOrder().getInsuranceDiscounts())) {
            retailInsuranceDiscountsService.returnProcess(saleOrder, retailReturn.getSaleOrder());
        }
    }

    /**
     * 获取定价过程
     *
     * @param product 商品编码
     * @param deptId  部门编码
     * @return JSONObject
     */
    private JSONObject getPrice(Product product, String deptId) {
        Store store = SpringManager.getBean(StoreRepository.class).findOne(deptId);

        JSONObject newXS51Map = getNewXS51Map(MapUtil.mapper(
                "MDID", store.getDept().getId(),
                "PLID", product.getClassify().getId(),
                "SPID", product.getId(),
                "PPID", product.getBrand().getId(),   //品牌找品质
                "XSZZID", store.getCompany().getId(),
                "GSID", store.getCompany().getId(),
                "CGZZID", "1007",
                "YYMS", store.getCompany().getParty().getCorporate().getOperation().getCode(),
                "SYGSID", "1007",
                "SQID", store.getBusinessCircle() == null ? null : store.getBusinessCircle().getId(),   // 商圈
                "XYGSID", store.getCompany().getId()
        ));

        JSONObject re1 = getXS51Price(newXS51Map);
        if (re1.getString("P001") == null) throw new RuntimeException("未找到价格文件");
        return re1;
    }

    private JSONObject getNewXS51Map(Map map) {
        JSONObject result = new JSONObject();
        result.put("conditionStrategyId", "XS51");
        result.put("SYS_RQ", new Date());
        result.put("SYS_NO_CHECK", "CAR_LICENSE");

        result.put("DEPT_ID", map.get("MDID") == null ? null : map.get("MDID"));
        result.put("COMPANY_ID", map.get("GSID") == null ? null : map.get("GSID"));

        result.put("PRODUCT_ID", map.get("SPID") == null ? null : map.get("SPID"));
        result.put("BRAND_ID", map.get("PPID") == null ? null : map.get("PPID"));
        result.put("CLASSIFY_ID", map.get("PLID") == null ? null : map.get("PLID"));

        result.put("SAL_COMPANY_ID", map.get("XYGSID") == null ? null : map.get("XYGSID"));
        result.put("PUR_COMPANY_ID", map.get("CGZZID") == null ? null : map.get("CGZZID"));
        result.put("BUSINESS_CIRCLE_ID", map.get("SQID") == null ? null : map.get("SQID"));

        result.put("OPERATION", map.get("YYMS") == null ? null : map.get("YYMS"));

        return result;
    }

    private JSONObject getXS51Price(Map map){
        Object obj = this.invoke("condition.execConditionStrategy", map);
        return new JSONObject(MapUtil.mapped(obj));
    }

    @Override
    public void afterSave(RetailOrder retailOrder) {
        retailOrder.setState("done");
    }

    @Override
    public boolean support(String orderType) {
        return "retailReturn".equals(orderType);
    }
}
